<template>
  <div class="dept-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">部门管理</h1>
      <el-button 
        type="primary" 
        class="add-btn" 
        @click="openDialog"
        :loading="dialogLoading"
      >
        <el-icon><Plus /></el-icon>
        <span>新增部门</span>
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="部门名称">
          <el-input 
            v-model="searchKeyword" 
            placeholder="请输入部门名称" 
            clearable 
            @keyup.enter="searchDept"
            class="search-input"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="searchDept"
            class="search-btn"
          >
            <el-icon><Search /></el-icon>
            <span>查询</span>
          </el-button>
          <el-button 
            @click="resetSearch"
            class="reset-btn"
          >
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格区域 -->
    <el-card class="data-card">
      <el-table 
        :data="tableData" 
        stripe 
        border 
        fit
        highlight-current-row
        class="dept-table"
        @row-click="handleRowClick"
        :loading="tableLoading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="部门名称" min-width="200" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" min-width="200" align="center" />
        <el-table-column label="操作" min-width="200" align="center">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="openEditDialog(scope.row)"
              class="action-btn edit-btn"
            >
              <el-icon><Edit /></el-icon>
              <span>修改</span>
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteDept(scope.row.id, scope.row.name)"
              class="action-btn delete-btn"
            >
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        />
      </div>
    </el-card>

    <!-- 新增部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增部门"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><OfficeBuilding /></el-icon>
        <span>新增部门</span>
      </template>
      <el-form
        :model="deptForm"
        :rules="rules"
        ref="deptFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="deptForm.createTime"
            type="datetime"
            placeholder="选择创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="deptForm.updateTime"
            type="datetime"
            placeholder="选择更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="addDept"
          class="dialog-btn confirm-btn"
          :loading="dialogLoading"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改部门对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改部门"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><OfficeBuilding /></el-icon>
        <span>修改部门</span>
      </template>
      <el-form
        :model="editDeptForm"
        :rules="rules"
        ref="editDeptFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editDeptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="editDeptForm.createTime"
            type="datetime"
            placeholder="选择创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="editDeptForm.updateTime"
            type="datetime"
            placeholder="选择更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="updateDept"
          class="dialog-btn confirm-btn"
          :loading="dialogLoading"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { DeptModelArray } from '@/api/model/model'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Delete, 
  OfficeBuilding, Close, Check
} from '@element-plus/icons-vue'

// 状态管理
const dialogLoading = ref(false)
const tableLoading = ref(false)

// 存储所有部门数据
const allDeptData = ref<DeptModelArray>([])

// 分页相关数据
const currentPage = ref(1)        // 当前页码
const pageSize = ref(5)           // 每页显示数量

// 查询关键字
const searchKeyword = ref('')

// 计算当前页要显示的数据
const tableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allDeptData.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(allDeptData.value.length / pageSize.value)
})

// 计算总记录数
const total = computed(() => {
  return allDeptData.value.length
})

// 加载所有部门数据
const loadAllData = async () => {
  tableLoading.value = true
  try {
    const result = await axios.get('http://localhost:8080/dept')
    allDeptData.value = result.data.data || []
  } catch (error) {
    console.error('加载部门数据失败', error)
    ElMessage.error('加载部门数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 查询部门方法
const searchDept = async () => {
  if (!searchKeyword.value.trim()) {
    // 如果查询关键字为空，则加载所有数据
    await loadAllData()
    currentPage.value = 1
    return
  }
  
  tableLoading.value = true
  try {
    const result = await axios.get(`http://localhost:8080/dept/${searchKeyword.value}`)
    if (result.data.data) {
      // 将查询结果放入数组，以便分页组件正常工作
      allDeptData.value = [result.data.data]
    } else {
      allDeptData.value = []
      ElMessage.warning('未找到匹配的部门')
    }
    currentPage.value = 1
  } catch (error) {
    console.error('查询部门失败', error)
    ElMessage.error('查询部门失败')
  } finally {
    tableLoading.value = false
  }
}

// 重置查询
const resetSearch = async () => {
  searchKeyword.value = ''
  await loadAllData()
  currentPage.value = 1
}

// 钩子函数
onMounted(() => {
  loadAllData()
})

// 控制新增对话框显示隐藏
const dialogVisible = ref(false)
// 控制修改对话框显示隐藏
const editDialogVisible = ref(false)

// 新增表单数据对象
const deptForm = ref({
  name: '',
  createTime: '',
  updateTime: ''
})
// 修改表单数据对象
const editDeptForm = ref({})

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '部门名称长度在2-20个字符之间', trigger: 'blur' }
  ],
  createTime: [
    { required: true, message: '创建时间不能为空', trigger: 'change' }
  ],
  updateTime: [
    { required: true, message: '更新时间不能为空', trigger: 'change' }
  ]
})

// 打开新增对话框并初始化表单
const openDialog = () => {
  const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
  deptForm.value = {
    name: '',
    createTime: now,
    updateTime: now
  }
  dialogVisible.value = true
}

// 打开修改对话框并填充数据
const openEditDialog = (dept: any) => {
  editDeptForm.value = {
    id: dept.id,
    name: dept.name,
    createTime: dept.createTime,
    updateTime: dept.updateTime
  }
  editDialogVisible.value = true
}

// 新增部门方法
const addDept = async () => {
  dialogLoading.value = true
  try {
    const { data } = await axios.post('http://localhost:8080/dept', deptForm.value)
    
    ElMessage.success('部门添加成功')
    dialogVisible.value = false
    await loadAllData() // 重新加载所有数据
    currentPage.value = 1 // 重置到第一页
    
  } catch (error) {
    console.error('部门添加失败', error)
    ElMessage.error('部门添加失败')
  } finally {
    dialogLoading.value = false
  }
}

// 修改部门方法
const updateDept = async () => {
  dialogLoading.value = true
  try {
    const { data } = await axios.put('http://localhost:8080/dept', editDeptForm.value)
    
    ElMessage.success('部门修改成功')
    editDialogVisible.value = false
    await loadAllData() // 重新加载所有数据
    
  } catch (error) {
    console.error('部门修改失败', error)
    ElMessage.error('部门修改失败')
  } finally {
    dialogLoading.value = false
  }
}

// 页码变更事件
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 每页条数变更事件
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

// 删除部门方法
const deleteDept = (id: number, name: string) => {
  ElMessageBox.confirm(
    `确定要删除部门【${name}】吗？删除后将无法恢复。`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      showClose: false
    }
  ).then(async () => {
    try {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      
      await axios.delete(`http://localhost:8080/dept/${id}`)
      ElMessage.success('部门删除成功')
      await loadAllData() // 重新加载所有数据
      
      // 如果删除后当前页没有数据，回到前一页
      if ((currentPage.value - 1) * pageSize.value >= total.value - 1) {
        currentPage.value = Math.max(1, currentPage.value - 1)
      }
      
      loading.close()
    } catch (error) {
      console.error('部门删除失败', error)
      ElMessage.error('部门删除失败')
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  })
}

// 表格行点击事件
const handleRowClick = (row: any) => {
  // 可以添加行点击后的操作，例如查看详情
  console.log('Row clicked:', row)
}

// 对话框关闭前处理
const handleDialogClose = (done: () => void) => {
  // 可以添加关闭前的确认或清理操作
  done()
}
</script>

<style scoped>
/* 引入Tailwind CSS工具类 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .transition-all-300 {
    transition: all 0.3s ease;
  }
  .shadow-hover {
    transition: box-shadow 0.3s ease, transform 0.3s ease;
  }
  .shadow-hover:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
  }
}

/* 页面整体样式 */
.dept-management-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #334155;
  margin: 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 24px;
  background-color: #4f46e5;
  margin-right: 10px;
  border-radius: 2px;
}

/* 搜索卡片样式 */
.search-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  padding: 16px 20px;
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  padding-left: 10px;
  transition: all 0.2s;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #4f46e5;
}

.search-icon {
  color: #94a3b8;
}

.search-btn,
.reset-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
}

.search-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.search-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}

.reset-btn {
  margin-left: 10px;
}

.reset-btn:hover {
  color: #4f46e5;
  border-color: #4f46e5;
}

/* 新增按钮样式 */
.add-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #10b981;
  border-color: #10b981;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.add-btn:hover {
  background-color: #059669;
  border-color: #059669;
  transform: translateY(-1px);
}

.add-btn el-icon {
  margin-right: 6px;
}

/* 数据卡片样式 */
.data-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 220px); /* 根据实际布局调整高度 */
}

.data-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.dept-table {
  flex: 1;
  overflow: auto;
}

.dept-table :deep(.el-table__header) {
  background-color: #f1f5f9;
}

.dept-table :deep(.el-table__header th) {
  font-weight: 600;
  color: #334155;
}

.dept-table :deep(.el-table__row) {
  transition: all 0.2s;
}

.dept-table :deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

.dept-table :deep(.el-table__cell) {
  padding: 12px 0;
}

/* 操作按钮样式 */
.action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
  margin: 0 4px;
}

.action-btn el-icon {
  margin-right: 4px;
}

.edit-btn {
  background-color: #e0f2fe;
  border-color: #e0f2fe;
  color: #0284c7;
}

.edit-btn:hover {
  background-color: #bae6fd;
  border-color: #bae6fd;
}

.delete-btn {
  background-color: #fee2e2;
  border-color: #fee2e2;
  color: #ef4444;
}

.delete-btn:hover {
  background-color: #fecaca;
  border-color: #fecaca;
}

/* 分页样式 */
.pagination-container {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: white;
  border-top: 1px solid #e2e8f0;
}

/* 对话框样式 */
.form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.form-dialog :deep(.el-dialog__header) {
  background-color: #f8fafc;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
}

.form-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #334155;
  display: flex;
  align-items: center;
}

.form-dialog :deep(.el-dialog__title) el-icon {
  margin-right: 8px;
  color: #4f46e5;
}

.form-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #475569;
}

.dialog-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  border: 1px solid #e2e8f0;
  color: #64748b;
}

.cancel-btn:hover {
  border-color: #4f46e5;
  color: #4f46e5;
}

.confirm-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.confirm-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}
</style>